const express = require('express');
const userModel = require('../models/users');

const usersRoute = express.Router();

usersRoute.post('/create', async (req, res) => {
  const {username, password} = req.body;
  if (!username || !password) {
    return res.status(400).json({msg: '用户名或密码错误'});
  }

  let user = await userModel.findOne({username});
  if (user) {
    return res.status(400).json({msg: '用户已存在'});
  }
  user = await userModel.create({username, password});
  return res.json(user);
});

usersRoute.post('/login', async (req, res) => {
  const {username, password} = req.body;
  if (!username || !password) {
    return res.status(400).json({msg: '用户名或密码错误'});
  }
  let user = await userModel.findOne({username});
  if (user) {
    return res.json(user);
  }
  return res.status(400).json({msg: '用户名或密码错误'});
});

usersRoute.get('/list', async (req, res) => {
  const result = await userModel.find();
  return res.json(result);
});


module.exports = usersRoute;

